package com.leanit.pmc.reg.service;

import com.leanit.pmc.center.enterprise.EnterPriseInfo;
import com.leanit.pmc.common.dao.CommonDao;
import com.leanit.pmc.common.util.FreeMarkerUtil;
import com.leanit.pmc.common.util.LeanItStringUtil;
import com.leanit.pmc.common.util.MD5Encrypt;
import com.leanit.pmc.common.util.MailSender;
import com.leanit.pmc.reg.bean.*;
import com.leanit.pmc.reg.dao.RegDao;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录controller
 *
 * @author
 */
@Service
public class RegService {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    CommonDao commonDao;
    @Autowired
    RegDao regDao;
    @Value("${reg.addr}")
    private String regAddr;
    @Value("${default.roles}")
    private String defaultRoles;
    @Value("${default.job}")
    private String defaultJob;
    @Value("${default.child.job}")
    private String defaultChildJob;

    /**
     * 验证邮箱，邮箱不能为空，邮箱格式必须正确，邮箱可以正确发送
     *
     * @param mail
     * @return
     */
    public String sendMail(String mail) throws IOException, TemplateException {
        if (StringUtils.isEmpty(mail)) {
            return "邮箱不能为空";
        }
        return hasRegistedMail(mail);
    }

    /**
     * 校验邮箱是否注册过,如果没有注册，记录并发送邮件
     *
     * @param mail
     * @return
     */
    private String hasRegistedMail(String mail) throws IOException, TemplateException {
        SysUser qryUser = new SysUser();
        qryUser.setEmail(mail);
        if (commonDao.qryCountCommon("sys_user", qryUser) > 0) {
            return "该邮箱已经被注册，请使用其他邮箱";
        }
        if (regDao.qryMailSend(mail) > 0) {
            return "请不要在一分钟内重复注册,请登录邮箱查收是否收到激活邮件";
        }

        String mailKey = generateMailKey(mail);
        RegMail qryMail = new RegMail();
        qryMail.setMail(mail);
        RegMail regMail = commonDao.qryOneCommon("reg_mail", qryMail, " reg_date desc");
        if (null == regMail) {
            regMail = new RegMail();
            regMail.setMail(mail);
            regMail.setMailKey(mailKey);
            regMail.setStatus(1);
            commonDao.insertCommon("reg_mail", regMail);
        } else {
            String now = LeanItStringUtil.getNowTime("yyyy-MM-dd HH:mm:ss");
            mailKey=regMail.getMailKey();
            regMail.setMailSendTime(now);
            regMail.setRegDate(now);
            regMail.setStatus(1);
            commonDao.updateCommon("reg_mail", regMail, " where mail=#{updateObj.mail}");
        }
        MailSender.sendMail(mail, "请继续完成您在单一窗口的注册", createMail(regMail.getMailKey()));

        return "success"+ mailKey;
    }

    /**
     * 创建邮件
     *
     * @param mailKey
     * @return
     */
    private String createMail(String mailKey) throws IOException, TemplateException {
        Map<String, Object> mailMap = new HashMap<>();
        mailMap.put("mailKey", mailKey);
        mailMap.put("regAddr", regAddr);
        return FreeMarkerUtil.processTemplate("MAIL_TEMPLATE_REG.xml", mailMap);
    }

    /**
     * 生成mailKey
     *
     * @param mail
     * @return
     */
    private String generateMailKey(String mail) {
        return MD5Encrypt.getMD5(mail + LeanItStringUtil.generateRandomStr(8)) + "_" + LeanItStringUtil.generateRandomStr(7);
    }

    /**
     * 根据mailKey获取mail
     *
     * @param mailKey
     * @return
     */
    public RegMail getRegMail(String mailKey) {
        RegMail regMail = null;
        if (StringUtils.isNotEmpty(mailKey)) {
            RegMail qryMail = new RegMail();
            qryMail.setStatus(1);
            qryMail.setMailKey(mailKey);
            regMail = commonDao.qryOne("reg_mail", qryMail, " reg_date desc");
        }
        return regMail;
    }

    /**
     * 发送邮件
     *
     * @param mail
     * @param mailKey
     * @return
     */
    public String sendMail(String mail, String mailKey) throws IOException, TemplateException {
        if (validMailKey(mail, mailKey)) {
            return sendMail(mail);
        }
        return "无效的发送邮件申请";
    }

    /**
     * 验证mailKey
     *
     * @param mail
     * @param mailKey
     * @return
     */
    public boolean validMailKey(String mail, String mailKey) {
        return regDao.qryMailKey(mail, mailKey) > 0;
    }

    /**
     * 保存注册用户信息
     *
     * @param regInfo
     * @return
     */
    public String regUsr(RegVO regInfo) {

        SysUser qryUser = new SysUser();
        qryUser.setEmail(regInfo.getMail());
        if (commonDao.qryCountCommonEqual("sys_user", qryUser) > 0) {
            return "该邮箱已经被注册，请不要重复注册";
        }
        qryUser.setEmail(null);
        qryUser.setUsername(regInfo.getUsername());
        if (commonDao.qryCountCommonEqual("sys_user", qryUser) > 0) {
            return "该用户名已经被注册，请不要重复注册";
        }
        qryUser.setUsername(null);
        qryUser.setMobilePhoneNumber(regInfo.getPhone());
        if (StringUtils.isNotEmpty(regInfo.getPhone()) && commonDao.qryCountCommonEqual("sys_user", qryUser) > 0) {
            qryUser.setMobilePhoneNumber(regInfo.getPhone());
            return "该手机号已经被注册，请不要重复注册";
        }
        SysAuth sysAuth = new SysAuth();
        SysUser user = regInfo.getSysUser();
        user.setId(commonDao.getSequenceValue("HIBERNATE_SEQUENCE"));
        EnterPriseInfo enterInfo = regInfo.getEnterInfo();
        SysOrganization sysOrg = regInfo.getSysOrganization();
        SysOrganization sysOrgQuery=new SysOrganization();
        sysOrgQuery.setOrganizationCode(sysOrg.getOrganizationCode());
        if (StringUtils.isNotEmpty(sysOrgQuery.getOrganizationCode()) && commonDao.qryCountCommonEqual("sys_organization", sysOrgQuery) > 0) {
            return "该社会信用代码或组织机构代码已经被注册，请不要重复注册";
        }

        SysOrganization sysOrgQuery2=new SysOrganization();
        sysOrgQuery2.setName(sysOrg.getName());
        if (StringUtils.isNotEmpty(sysOrgQuery2.getName()) && commonDao.qryCountCommonEqual("sys_organization", sysOrgQuery2) > 0) {
            return "该公司名称已经被注册，请不要重复注册";
        }
        sysOrg.setId(commonDao.getSequenceValue("HIBERNATE_SEQUENCE"));
        sysOrg.setWeight(regDao.getOrgWeight());
        SysUserOrganizationJob sysUserOrganizationJob = new SysUserOrganizationJob();
        sysUserOrganizationJob.setJobId(defaultJob);
        sysUserOrganizationJob.setOrganizationId(sysOrg.getId());
        sysUserOrganizationJob.setUserId(user.getId());
        sysAuth.setUserId(user.getId());
        sysAuth.setOrganizationId("0");
        sysAuth.setJobId("0");
        sysAuth.setGroupId("0");
        sysAuth.setRoleIds(defaultRoles);
        sysAuth.setType("user");
        commonDao.insertCommon("sys_organization", sysOrg);
        commonDao.insertCommon("sys_user", user);
        commonDao.insertCommon("sys_enterprise_info", enterInfo);
        commonDao.insertCommon("sys_user_organization_job", sysUserOrganizationJob);
        commonDao.insertCommon("sys_auth", sysAuth);
        return "success";
    }

    /**
     * 添加子用户
     *
     * @param userName
     * @param parentId
     * @param mail
     * @param phone
     * @return
     */
    public String addChildUsr(String userName, String parentId, String mail, String phone, String password) {
        SysUser qryUser = new SysUser();
        qryUser.setEmail(mail);
        if (StringUtils.isNotEmpty(mail) && commonDao.qryCountCommonEqual("sys_user", qryUser) > 0) {
            return "该邮箱已经被注册，请不要重复注册";
        }
        qryUser.setEmail(null);
        qryUser.setUsername(userName);
        if (StringUtils.isNotEmpty(userName) && commonDao.qryCountCommonEqual("sys_user", qryUser) > 0) {
            return "该用户名已经被注册，请不要重复注册";
        }
        qryUser.setUsername(null);
        qryUser.setMobilePhoneNumber(phone);
        if (StringUtils.isNotEmpty(phone) && commonDao.qryCountCommonEqual("sys_user", qryUser) > 0) {
            return "该手机号已经被注册，请不要重复注册";
        }
        SysAuth sysAuth = new SysAuth();
        qryUser.setUsername(null);
        qryUser.setMobilePhoneNumber(null);
        qryUser.setId(parentId);
        SysUser user = commonDao.qryOne("sys_user", qryUser, "");
        if (StringUtils.isEmpty(parentId) || null == user) {
            return "父用户不存在";
        }
        user.setId(commonDao.getSequenceValue("HIBERNATE_SEQUENCE"));
        user.setUsername(userName);
        user.setEmail(mail);
        user.setCnName(userName);
        user.setMobilePhoneNumber(phone);
        user.setPassword(MD5Encrypt.getMD5(password));
        user.setCreateDate(null);
        SysUserOrganizationJob sysUserOrganizationJob = new SysUserOrganizationJob();
        sysUserOrganizationJob.setJobId(defaultChildJob);
        sysUserOrganizationJob.setOrganizationId(regDao.getOrgIdByUserId(parentId));
        sysUserOrganizationJob.setUserId(user.getId());
        sysAuth.setUserId(user.getId());
        sysAuth.setOrganizationId("0");
        sysAuth.setJobId("0");
        sysAuth.setGroupId("0");
        sysAuth.setRoleIds(defaultRoles);
        sysAuth.setType("user");
        SysUserChild sysUserChild = new SysUserChild();
        sysUserChild.setParentId(parentId);
        sysUserChild.setUserId(user.getId());
        commonDao.insertCommon("sys_user_child", sysUserChild);
        commonDao.insertCommon("sys_user", user);
        commonDao.insertCommon("sys_user_organization_job", sysUserOrganizationJob);
        commonDao.insertCommon("sys_auth", sysAuth);
        return "success";
    }
}
